package freejim.icu.highschoolhealthstatuspost.config;

import freejim.icu.highschoolhealthstatuspost.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;


import javax.annotation.Resource;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
@Order(101)
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.antMatcher("/admin/**").authorizeRequests()
                .antMatchers("/admin/login_backend").permitAll()
                .anyRequest()
                .hasAuthority("ADMIN").and()
                .formLogin()
                .loginPage("/admin/login_backend")
                .successHandler((req, res, authentication) -> {
                    PrintWriter out = res.getWriter();
                    out.write("ok");
                    out.flush();
                    out.close();
                }).and()
                .logout()
                .logoutUrl("/admin/logout")
                .logoutSuccessUrl("/admin/login_backend");
    }

    @Resource
    private ApplicationContext applicationContext;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService((UserService)applicationContext.getBean("userService"));
        auth.jdbcAuthentication().passwordEncoder((PasswordEncoder) applicationContext.getBean("passwordEncoder")).rolePrefix("");
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/img/**", "/**/*.png");
    }

}
